var settings = require('../config');
var util_tool = require('../utils');
var models = require("../models"),
    User = models.User,
    WCSession = models.WCSession;
var _ = require('underscore');
var debug = require('debug')('consultant:timer');
var util_tool = require('./index');
var async = require('async');
/**
 *定时器轮询status为1的会话是否已经超时
 */
setInterval(function () {
        //定时检查status为1的会话是否已经超时
        checktimeout();
        //定时统计用户评价
        statcomment();
    },
    settings.timer
);
/**
 * 用户会话超时统计
 */
function checktimeout() {
    var sessionDao = new WCSession();
    sessionDao.findSessionByStatus(1, function (err, sessions) {
        _.each(sessions, function (session, index, list) {
            //判断此对话是否包含了relet_date即已经续时的会话
            var checkdate;
            var timeoutdate;
            if (session.relet_date) {//如果用户已经续时，巡检超时的时间为relet_date
                checkdate = session.relet_date;
                timeoutdate = settings.wc_session_timeout * (session.relet_count + 1);
            } else {//如果用户未经续时，巡检超时的时间为build_date
                checkdate = session.build_date;
                timeoutdate = settings.wc_session_timeout;
            }
            var curdate = new Date();
            var diftime = (curdate - checkdate) / 1000;
            if (diftime > settings.wc_session_timeout) { //判断对话是否超时
                //如果会话已经超时，更新会话状态
                if(!session.room){
                    sessionDao.updateSessionBySendOpneId2(session.send_openid, function (err) {
                            if (err) {
                                debug("session timeout update fail", err);
                            } else {
                                //已经超时
                                debug("the session is timeout", session);
                                //给双方发超时通知
                                var msg1 = {
                                    sendopenid: session.send_openid,
                                    sendtextmsg: "系统：本次服务时间为" + timeoutdate / 60 + "分钟，已经超时。请您对本次服务进行评价，回复1代表“不满意”；2代表“一般”；3代表“满意”。"
                                }
                                new util_tool().sendText(msg1, function (err) {
                                        if (err) {
                                            debug("send message fail", err);
                                        } else {
                                            var msg2 = {
                                                sendopenid: session.receive_openid,
                                                sendtextmsg: "系统：会话有效时间为" + timeoutdate / 60 + "分钟，已经超时，对话结束。"
                                            }
                                            new util_tool().sendText(msg2, function (err) {
                                                if (err) debug("send message fail", err);
                                            })
                                        }
                                    }
                                )
                            }
                        }
                    )
                }
            }
            else if (settings.wc_session_timeout - diftime <= settings.notifytime) { //如果会话时间小于2分钟提醒用户
                if (session.notify_count == session.relet_count) { //如果通知次数等于续时次数时提醒超时
                    //发送通知前先判断该用户是否只有一个session存在，避免重复发送消息
                    if(!session.room){
                        sessionDao.updateSessionNotifyByOpendId(session.send_openid, function (err) {
                                if (err) {
                                    debug("updateSessionBySessionId is fail", err);
                                } else {
                                    var msglink = "<a href='http://117.78.6.144/relet?sendopenid=" + session.send_openid + "&receiveopenid=" + session.receive_openid + "'>续时</a>";
                                    var msg = {
                                        sendopenid: session.send_openid,
                                        sendtextmsg: "系统：本次对话还有" + settings.notifytime / 60 + "分钟就要超时，您希望续时吗？" + msglink
                                    }
                                    new util_tool().sendText(msg, function (err) {
                                        if (err) debug("send message fail", err);
                                    });
                                }
                            }
                        )
                    }
                }
            }
            else {
                debug("the session is not timeout");
            }
        })
    });
}
/**
 * 统计用户评价并设置用户权重
 * 10个咨询增加一点权重即weight+1，5个好评增加1点权重
 */
function statcomment() {
    async.waterfall([function (wcb) {
        //根据咨询师分组获得的平价分数和次数计算咨询师的权重
        new WCSession().findSessionGroupBy({
            'stat': 0,
            'comment': {
                $gt: 0
            }}, function (err, result) {
            if (result.length > 0) {
                var wcount = 0;
                async.whilst(
                    function () {
                        return wcount < result.length;
                    },
                    function (whcb) {
                        //10个好评给加3分权重算法：评价平均分*接诊数量比例
                        var weight = (result[wcount].sumComment / result[wcount].count) * (result[wcount].count / settings.statcomment);
                        var rweight = Math.round(weight * 100) / 100;
                        new User().updateUserWeightByOpenId({
                            "wcopenid": result[wcount]._id
                        }, {
                            "weight": rweight
                        }, function (err) {
                            if (err)debug('updateUserWeightByOpenId fail', err);
                            wcount++;
                            whcb();
                        })
                    },
                    function (err) {
                        wcb(err, result);
                    }
                );
            } else {
                wcb(err, result);
            }
        })
    }, function (result, wcb) {
        //修改会话的统计状态为已统计
        if (result.length > 0) {
            new WCSession().updateSessionCommon({stat: 0, status: 2}, {stat: 1}, true, function (err) {
                if (err)debug('updateSessionCommon stat fail', err);
                wcb(err, 'updated');
            });
        } else {
            debug('the stat result is null');
            wcb(null, 'no update');
        }
    }], function (err, result) {
        debug('update user stat success!!', result);
    })
}